package com.yzt.zhuju.base;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.alibaba.android.arouter.launcher.ARouter;
import com.yzt.zhuju.R;
import com.yzt.zhuju.application.BaseFra;
import com.yzt.zhuju.event.BaseBusEvent;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.voice.VoicePlayManager;
import com.yzt.p_base.AppUtils;
import com.yzt.zhuju.constants.PreferenceConstant;
import com.yzt.p_base.utils.KeyboardUtils;
import com.yzt.p_base.utils.SharedPreferenceUtil;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import rx.Subscription;
import rx.functions.Action1;

/**
 * author : bob
 * date   : 2022/11/29
 * desc   :
 */
public abstract class BaseFragment extends BaseFra {

    public static int PAGE_SIZE = 20;

    public int mCurrentPage = 1;

    public Handler handler = new MyHandler(this);

    public boolean isNetWorking;

    public boolean isViewLazyLoaded;

    protected boolean isVisibleToUser;

    private boolean isViewInitiated;

    private final List<Subscription> mSubscriptions = new ArrayList<>();

    private ViewTreeObserver.OnGlobalLayoutListener mOnGlobalLayoutListener;

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
    }

    @Override
    public int getPositionTag() {
        return -2;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewInitiated = true;
        if (isRegisterSoftInputChangeLister()) {
            keyboardHeight();
        }
    }

    public abstract int getLayoutId();

    public abstract void installViews();

    protected boolean isRegisterSoftInputChangeLister() {
        return true;
    }

    private int keyHeight = 0;

    protected void keyboardHeight() {
        mOnGlobalLayoutListener = KeyboardUtils.registerSoftInputChangedListener(mActivity, height -> {
            if (height > keyHeight) {
                SharedPreferenceUtil.getInstance().putValue(PreferenceConstant.KEYBOARD_HEIGHT, height);
                keyHeight = height;
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        KeyboardUtils.unRegisterSoftInputChangedListener(mActivity, mOnGlobalLayoutListener);
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        if (!loadLayoutLazy()) {
            setContentView(getLayoutId());
        }
        installViews();
        if (isVisibleToUser && !isViewLazyLoaded) {
            lazyLoadView();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        if (isViewInitiated && isVisibleToUser && !isViewLazyLoaded) {
            lazyLoadView();
        }

        if (!isViewInitiated && isVisibleToUser && !isNetWorking) {
            //代表第一个fragment
            handler.postDelayed(() -> {
                isNetWorking = true;
                netWorkRequest();
            }, 100);
            return;
        }
        if (isViewInitiated && isVisibleToUser && !isNetWorking) {
            isNetWorking = true;
            netWorkRequest();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!isViewInitiated && !hidden && !isNetWorking) {
            //代表第一个fragment
            handler.postDelayed(() -> {
                isNetWorking = true;
                netWorkRequest();
            }, 100);
            return;
        }
        if (isViewInitiated && !hidden && !isNetWorking) {
            isNetWorking = true;
            netWorkRequest();
        }
    }

    /**
     * 发送网络请求
     */
    public abstract void netWorkRequest();

    /**
     * 懒加载layout
     */
    protected boolean loadLayoutLazy() {
        return false;
    }

    /**
     * 懒加载初始化
     */
    protected void lazyLoadView() {
        isViewLazyLoaded = true;
        if (loadLayoutLazy()) {
            setContentView(getLayoutId());
        }
    }

    public View getErrorView(String text) {
        return getEmptyView(R.mipmap.icon_network_error, text);
    }

    public View getEmptyView() {
        return getEmptyView(R.mipmap.icon_empty_data, getString(R.string.page_empty));
    }

    public View getEmptyView(String text) {
        return getEmptyView(R.mipmap.icon_empty_data, text);
    }


    public View getEmptyView(int imageId, String text) {
        if (mActivity == null) {
            return new View(AppUtils.getContext());
        }
        View view = LayoutInflater.from(mActivity).inflate(R.layout.layout_empty_view, null);
        view.findViewById(R.id.empty_layout).setOnClickListener(v -> netWorkRequest());
        ImageView emptyImage = view.findViewById(R.id.iamge_empty);
        TextView emptyText = view.findViewById(R.id.text_empty);
        emptyImage.setImageResource(imageId);
        emptyText.setText(text);
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        for (Subscription subscription : mSubscriptions) {
            if (subscription == null) {
                continue;
            }
            if (subscription.isUnsubscribed()) {
                continue;
            }
            subscription.unsubscribe();
        }
        mSubscriptions.clear();

        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onStop() {
        super.onStop();
        VoicePlayManager.getInstance().stopPlay();
    }

    public void refreshScreen() {

    }

    private static class MyHandler extends Handler {

        WeakReference<Fragment> reference;

        public MyHandler(Fragment fragment) {
            reference = new WeakReference<>(fragment);
        }
    }

    protected <E extends BaseBusEvent> void observerRxBus(Class<E> busClass, Action1<E> onNext) {
        Subscription subscription = RxBus.getDefault().observerRxBus(busClass, onNext);
        mSubscriptions.add(subscription);
    }

    protected <E extends BaseBusEvent> void observerRxBusSticky(Class<E> busClass, Action1<E> onNext) {
        Subscription subscription = RxBus.getDefault().observerRxBusSticky(busClass, onNext);
        mSubscriptions.add(subscription);
    }
}
